package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

import static com.sky.constant.AutoFillConstant.*;

/**
 * 公共字段处理切面
 */
@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    // 公共切入点表达式
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    private void pt() {
    }

    @Before("pt()")
    public void insertAndUpdateAop(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        // 获取调用方法注解Value值
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = methodSignature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();

        // 获取Entity参数对象
        Object[] targets = joinPoint.getArgs();

        // 健壮性判断
        if (targets == null || targets.length == 0) {
            return;
        }

        // 获取所需数据
        Object target = targets[0];
        LocalDateTime now = LocalDateTime.now();
        Long userId = BaseContext.getCurrentId();

        // 获取setUpdateTime方法和setUpdateUser方法映射对象
        Method setUpdateTime = target.getClass().getMethod(SET_UPDATE_TIME, LocalDateTime.class);
        Method setUpdateUser = target.getClass().getMethod(SET_UPDATE_USER, Long.class);

        // 根据对应的操作类型，为对应的属性赋值
        if(operationType == OperationType.INSERT) {
            // 获取setCreateTime方法和setCreateUser方法映射对象
            Method setCreateTime = target.getClass().getMethod(SET_CREATE_TIME, LocalDateTime.class);
            Method setCreateUser = target.getClass().getMethod(SET_CREATE_USER, Long.class);

            // 进行赋值操作
            setCreateTime.invoke(target, now);
            setCreateUser.invoke(target, userId);
            setUpdateTime.invoke(target, now);
            setUpdateUser.invoke(target, userId);
        } else if(operationType == OperationType.UPDATE) {
            // 进行赋值操作
            setUpdateTime.invoke(target, now);
            setUpdateUser.invoke(target, userId);
        }
    }
}
